import { Request, toast, alert, copyText, parseTime } from '../../../utils/util.js'
let request = new Request()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId : 0,
    index : -1,
    showCancelConfirm : false,
    order : null,
    orderStatus : '',
    payType : {},
    payOrder : ''
  },

  copy () {
    copyText(this.data.payType.bank_account)
  },

  upload (e) {
    this.setData({ payOrder : e.detail.value})
  },

  cancelOrder () {
    this.setData({ showCancelConfirm : true})
  },

  cancelCallback (e) {
    if(e.detail == 1){
      this.setData({ showCancelConfirm: false })
      return
    }
    let pages = getCurrentPages()
    let page = pages[pages.length - 2]
    page.setData({ currentIndex: this.data.index})
    page.cancelCallback(e)
    wx.navigateBack({
      
    })
  },

  confirm () {
    let payOrder = this.data.payOrder
    if (payOrder === '') {
      toast('请上传支付凭证')
      return
    }

    request.post('order/pay', res => {
      if(res.success) {
        toast('确定成功')
        let pages = getCurrentPages()
        let page = pages[pages.length - 2]
        page.updateOrderList(this.data.index)
        wx.navigateBack({
        })
      }else{
        toast(res.msg)
      }
    }, {order : payOrder, id : this.data.orderId})
  },

  confirmComplete() { //确定收货
    let index = this.data.index
    wx.showModal({
      title: '确定收货',
      content: '请确定已经收到商品',
      success: res => {
        if (res.confirm) {
          let pages = getCurrentPages()
          let page = pages[pages.length - 2]
          page.completeOrder(index)
          wx.navigateBack({
            
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let orderId = options.orderId
    request.get('order/detail', res => {
      if(res.success){
        let order = res.data.order

        order.create_time = parseTime(order.create_time)
        order.merchant_confirm_time = parseTime(order.merchant_confirm_time)
        order.pay_time = parseTime(order.pay_time)
        order.deliver_time = parseTime(order.deliver_time)

        order.delivery = {
          consignee : order.consignee,
          mobile : order.mobile,
          province: order.province,
          city: order.city,
          district: order.district,
          address : order.address,
          remarks : order.remarks
        }
        this.setData({ order: order, orderStatus : order.status})
        if(order.status == 1) { //待支付,取商家支付信息
          let req = new Request()
          req.get('order/merchantpay', res => {
            if(res.success) {
              res.data.amount = res.data.amount * 1
              res.data.delivery_fee = res.data.delivery_fee * 1
              this.setData({ payType : res.data})
            }
          }, { id: orderId})
        }

      }else{
        alert(res.msg)
      }
    }, { id: orderId}).showLoading()

    this.setData({ orderId: orderId, index : options.index})
  }
})